package edu.sctu.practice.class02.xuqianlan.assign.assign08.test3;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by hp on 2015/12/21.
 */
public class Client extends Frame implements ActionListener,Runnable{
    Button b=new Button("获取图像");
    ImageCanvas canvas;
    Client(){
        super("I am a client");
        setSize(320, 200);
        setVisible(true);
        b.addActionListener(this);
        add(b, BorderLayout.NORTH);
        canvas=new ImageCanvas();
        add(canvas, BorderLayout.CENTER);
        Thread thread=new Thread(this);
        validate();
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        thread.start();
    }
    public void actionPerformed(ActionEvent event){
        byte b[]="请发图".trim().getBytes();
        try{
            InetAddress address=InetAddress.getByName("127.0.0.1");
            DatagramPacket data=new DatagramPacket(b,b.length,address,1234);//创建数据包，该数据包的目标地址和端口分别是
            //address和1234，其中的数据为数组b中的全部字节。
            DatagramSocket mailSend=new DatagramSocket();
            mailSend.send(data);
        }catch (Exception e){}
    }
    public void run(){
        DatagramPacket pack=null;
        DatagramSocket mailReceive=null;
        byte b[]=new byte[8192];
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        try{
            pack=new DatagramPacket(b,b.length);
            mailReceive=new DatagramSocket(5678);
        }catch (Exception e){}
        try{
            while (true){
                mailReceive.receive(pack);
                String message=new String(pack.getData(),0,pack.getLength());
                if (message.startsWith("end")){
                    break;
                }
                out.write(pack.getData(),0,pack.getLength());
            }
            byte imagebyte[]=out.toByteArray();
            out.close();
            Toolkit tool=getToolkit();
            Image image=tool.createImage(imagebyte);
            canvas.setImage(image);
            canvas.repaint();
            validate();
        }catch (IOException e){}
    }

    public static void main(String[] args) {
        new Client();
    }
}
